<template>
	<view>
		<ls-page title="">
			<view class="contant">
				<view class="banner">
					<image v-if="activityList[0]?.activityImage" :src="activityList[0]?.activityImage"
						mode="widthFix" />
					<image v-else src="https://jtmc.oss-cn-hangzhou.aliyuncs.com/wmp/kbq/common/i_sign_back.png"
						mode="widthFix" />
				</view>
				<!-- 日历主体 -->
				<view class="calendar">
					<view class="TDate">
						{{ SignIn.memberName }}，
						<text class="TMonth">{{ month }}月</text>
						已累计签到
						<text class="TDay">{{ SignIn.signInCount }}</text>
						天
					</view>
					<view class="header">
						<view :class="(index == todayIndex && isTodayWeek ? 'weekMark' : '') + ' '" v-for="(item, index) in date" :key="index">
							{{ item }}
							<view>	
							</view>
						</view>
					</view>
					<view class="date-box">
						<block v-for="(item, index) in dateArr" :key="index">
							<view :class="(isToday > item.isToday ? 'agoDays' : 'nextDays') + ' ' + (isToday == item.isToday ? 'nowDay' : '')">
								<view v-if="item.dateNum" :class="(item.choose ? 'date-top date-topT' : 'date-top') + ' ' + (dayIndex == index ? 'dayIndex' : '')"
									@click="getToDay(item,index)">
									<view v-if="isToday > item.isToday">
										<image v-if="item.choose"
											src="https://jtmc.oss-cn-hangzhou.aliyuncs.com/wmp/images/signin/dollar.png"
											mode="scaleToFill" />
										<image v-if="!item.choose"
											src="https://oss.jtmckj.com/wmp/qnjg/center/dollar_gay.png"
											mode="scaleToFill" />
										<view v-if="item.choose">已签</view>
										<view v-if="!item.choose" style="color: #999999">未签</view>
									</view>
									<view v-if="isToday < item.isToday">
										<image
											src="https://jtmc.oss-cn-hangzhou.aliyuncs.com/wmp/images/signin/dollar.png"
											mode="scaleToFill" />
									</view>
									<view v-if="isToday == item.isToday">
										<image
											src="https://jtmc.oss-cn-hangzhou.aliyuncs.com/wmp/images/signin/dollar.png"
											mode="scaleToFill" />
										<view v-if="item.choose">已签</view>
										<view v-if="!item.choose" style="color: #ff3333">今天</view>
									</view>
								</view>
								<view class="date-head font28" :data-year="year" :data-month="month"
									:data-datenum="item.dateNum">
									<view>{{ item.dateNum }}</view>
								</view>
							</view>
						</block>
					</view>
					<view class="calendar_title layer_center">
						<view class="icon" @click="lastMonth">
							<image src="https://oss.jtmckj.com/wmp/kbq/common/i_radio_red-left.png" />
						</view>
						<view class="nowDtae font60">{{ year }}年{{ month }}月</view>
						<view class="icon" @click="nextMonth">
							<image src="https://oss.jtmckj.com/wmp/kbq/common/i_radio_red-right.png" />
						</view>
					</view>
					<view class="center flex_center" @click="signIn" v-if="hasSign == false && buqian == false">
						<view class="center_text font32">立即签到</view>
					</view>
					<view class="center flex_center" @click="signIn" v-if="hasSign == false && buqian == true">
						<view class="center_text font32">补签</view>
					</view>
					<view class="center flex_center" style="background: linear-gradient(180deg, #ff7733, #cc0000)"
						@click="alreadySign" v-if="hasSign == true">
						<view class="center_text center_texts font32">已签到</view>
					</view>
				</view>

				<view class="rewardContent">
					<view class="rewardTitle">累计签到可领取奖励</view>
					<view class="rewardList" v-if="activityList[0]">
						<view class="rewardItem" v-for="(item, index) in activityList[0].awardList" :key="index">
							<text class="itemAbsT" v-if="item.isGetAward == true">已获得</text>
							<text class="itemAbsF" v-if="item.isGetAward == false">未获得</text>
							<view style="color: #ff4000">{{ item.ticketName }}</view>
							<view style="color: #da7715">奖品*{{ item.awardCount }}</view>
							<view class="rewardItem-day" style="font-size: 24rpx">
								{{ item.awardTypeDesc }}{{ item.signInDay }}天
							</view>
						</view>
						<view style="width: 31.5%"></view>
					</view>
				</view>
				<view class="ruleContent">
					<view class="ruleTitle">签到规则</view>
					<view class="ruleText">{{ activityList[0]?.activityRule }}</view>
				</view>
			</view>
			<!-- <view class="bottom flex_center">
    <view class="bottom_text font36">本月累计签到<text>X</text>次</view>
    <view class="bottom_text font36">未签到<text>X</text>次</view>
</view> -->
		</ls-page>
	</view>
</template>

<script setup>
	import { ref } from 'vue';
	import { onLoad, onUnload, onShow, onHide } from '@dcloudio/uni-app';
	import { HFiveAppObjProcess, HFiveMemberAppObjProcess, GetMinimsgTemplate } from '@/api/public.js'
	import dayjs from 'dayjs'
	import { debounce } from '@/until/tools.js'
	
	// -------------------------------------------------------初始化数据-----------------------------------------------------
	const shopInfo = uni.getStorageSync('shopInfo') //门店信息
	console.log(shopInfo, 'shopInfo')
	const userInfo = uni.getStorageSync('userInfo') //用户信息

	const year = ref(0);
	const month = ref(0);
	const date = ref(['周日', '周一', '周二', '周三', '周四', '周五', '周六']);
	const dateArr = ref([]); // 本月的签到情况
	const isToday = ref(0);
	const isTodayWeek = ref(false);
	const todayIndex = ref(0);
	const dayIndex = ref(null);

	const latitude = ref('')
	const longitude = ref('')

	// 其他状态变量
	const yesDate = ref([]);
	const signinNow = ref(false);
	const activityCode = ref('');
	const signInTime = ref('');
	const hasSign = ref(false); // 是否已签到
	const buqian = ref(false); // 补签
	const SignIn = ref({})
	const activityList = ref([])
	// -------------------------------------------------------初始化数据-----------------------------------------------------

	onLoad((options) => {
		let now = new Date();
		let currentYear = now.getFullYear(); // 当前年份
		let currentMonth = now.getMonth() + 1; // 当前月份
		let currentDay = now.getDate().toString().padStart(2, '0'); // 当前日期
		// 格式化月份，确保是两位数
		currentMonth = currentMonth < 10 ? '0' + currentMonth : currentMonth;
		year.value = currentYear;
		month.value = Number(currentMonth);
		isToday.value = '' + year.value + currentMonth + currentDay; // 构建完整的日期格式（yyyyMMdd）
		// 调用初始化日期函数
		dateInit();
		// 调用其他相关的函数
		yesdate();
		GetActivityList();
	});

	onShow(() => {

	});

	//--------------------------------------------------------------------------------------------点击获取今日信息----------------------------------------------------------------------------------
	const getToDay = (v, k) => {
		let actday = v
		let today = isToday.value
		// console.log(actday, 'actday');
		// console.log(today, 'today');
		if (actday.isToday > today) { // 如果点击的日期超过今天
			return
		}
		let newActDay = actday.isToday.slice(0, 4) + '-' + actday.isToday.slice(4, 6) + '-' + actday.isToday.slice(6,
			8)
		let newToDay = today.slice(0, 4) + '-' + today.slice(4, 6) + '-' + today.slice(6, 8)
		// 如果小于当前日期并且未签到 可以补签(?)
		if (new Date(newActDay).getTime() <= new Date(newToDay).getTime() && !actday.choose) {
			dayIndex.value = k
			signInTime.value = newActDay
			hasSign.value = false
			buqian.value = true
		} else {
			buqian.value = false
		}
		if (actday.isToday == today) { // 如果点击的是今天 取消其它的选中样式
			dayIndex.value = -1
		}

		if (actday.choose) { // 如果已签到
			hasSign.value = true
		} else {
			hasSign.value = false
		}
	}
    
	//--------------------------------------------------------------------------------------------签到----------------------------------------------------------------------------------
	const signIn = () => {
		uni.showLoading({
			title: "加载中",
			mask: true,
		});
		HFiveMemberAppObjProcess({"functionName": "AddSignIn_H5","contentData": {"activityCode": activityCode.value,"signInTime": signInTime.value}}).then(res => {
			uni.hideLoading();
			uni.showToast({
				icon: 'none',
				title: res.data
			})
			dateInit(year.value, month.value - 1)
		})
		// let t = this;
		// t.getLocation();
	}
   
	//--------------------------------------------------------------------------------------------获取用户当前地理位置----------------------------------------------------------------------------------
	const getLocation = () => {
		wx.getFuzzyLocation({
			type: 'wgs84',
			success: (res) => {
				var latitude = res.latitude
				var longitude = res.longitude
				latitude.value = latitude
				longitude.value = longitude
				activeSign()
			}
		})
	}
    
	//----------------------------------------------------------------------------是否可以签到 (根据离店距离判断是否可以签到)-----------------------------------------------------------------------
	const activeSign = () => {
		let nowdate = isToday.value;
		let dateArr = dateArr.value;
		let yesDate = yesDate.value;
		for (var i = 0; i < dateArr.length; i++) {
			// console.log(nowdate,dateArr[i].isToday);
			if (dateArr[i].isToday == nowdate) {
				dateArr[i].choose = true;
				yesDate.push(nowdate);
				// $.successToast("签到成功")
				signinNow.value = true
				yesDate.value = yesDate

			}
		};
		dateArr.value = dateArr
	}

	// 签到过
	const alreadySign = () => {
		uni.showToast({ title: '今天已经签到过啦~', icon: 'none' });
	}

	// --------------------------------------------------------------------------------------------------已签到日期处理------------------------------------------------------------------------------
	const yesdate = () => {
		let updatedDateArr = [...dateArr.value]; // 创建副本防止直接修改原数据
		for (let i = 0; i < updatedDateArr.length; i++) {
			for (let j = 0; j < yesDate.value.length; j++) {
				if (updatedDateArr[i].isToday === yesDate.value[j]) {
					updatedDateArr[i].choose = true;
				}
			}
		}
		dateArr.value = updatedDateArr;
	};
    
	// ---------------------------------------------------------------------------------------初始化日历------------------------------------------------------------------------------
	const dateInit = (setYear, setMonth) => {
		let updatedDateArr = [];
		let now = setYear ? new Date(setYear, setMonth) : new Date();
		let year = setYear || now.getFullYear();
		let nextYear = 0;
		let month = setMonth || now.getMonth();
		let nextMonth = (month + 1) > 11 ? 1 : (month + 1);
		let startWeek = new Date(year, month, 1).getDay(); // 目标月1号对应的星期
		let dayNums = new Date(year, nextMonth, 0).getDate(); // 获取目标月有多少天
		let num = 0;

		if (month + 1 > 11) {
			nextYear = year + 1;
			dayNums = new Date(nextYear, nextMonth, 0).getDate();
		}

		let arrLen = startWeek + dayNums;
		for (let i = 0; i < arrLen; i++) {
			if (i >= startWeek) {
				num = i - startWeek + 1 < 10 ? '0' + String(i - startWeek + 1) : String(i - startWeek + 1);
				updatedDateArr.push({
					isToday: '' + year + ((month + 1) < 10 ? "0" + (month + 1) : (month + 1)) + num,
					dateNum: num,
					weight: 5,
					choose: ''
				});
			} else {
				updatedDateArr.push({});
			}
		}

		dateArr.value = updatedDateArr;

		let nowDate = new Date();
		let nowYear = nowDate.getFullYear();
		let nowMonth = nowDate.getMonth() + 1 < 10 ? '0' + (nowDate.getMonth() + 1) : (nowDate.getMonth() + 1);
		let nowWeek = nowDate.getDay();
		let getYear = setYear || nowYear;
		let getMonth = setMonth >= 0 ? (setMonth + 1) : nowMonth;

		if (nowYear == getYear && nowMonth == getMonth) {
			isTodayWeek.value = true;
			todayIndex.value = nowWeek;
		} else {
			isTodayWeek.value = false;
			todayIndex.value = -1;
		}

		let date = year + '-' + (month + 1);
		if (dateArr.value) {
			GetSignInRecord(dateArr.value, date);
		}
	};
    
	// ---------------------------------------------------------------------------------------获取活动列表------------------------------------------------------------------------------
	const GetActivityList = () => {
		HFiveMemberAppObjProcess({ "functionName": "GetActivityList_H5", "contentData": {}}).then(res => {
			if( res[0]) {
				activityCode.value = res[0].code
				activityList.value = res
			}
		})
	}
    
	// ---------------------------------------------------------------------------------------获取签到数据------------------------------------------------------------------------------
	const GetSignInRecord = (dateArr, date) => {
		HFiveMemberAppObjProcess({ "functionName": "GetSignInRecord_H5", "contentData": { "date": date } }).then(res => {
				if (res.signInList[res.signInList.length - 1].value) { // 判断今天是否签到
					hasSign.value = true
				}
				// 根据返回的数据将dateArr中标出已签（为true）
				dateArr.map(e => {
					res.signInList.map(i => {
						if (e.isToday == i.fullDate) {
							e.choose = i.value
						}
					})
				})
				SignIn.value = res
				dateArr.value = dateArr
			})
	}
   
   // ---------------------------------------------------------------------------------------上一月切换------------------------------------------------------------------------------
	const lastMonth = () => {
		//全部时间的月份都是按0~11基准，显示月份才+1
		let year1 = month.value - 2 < 0 ? year.value - 1 : year.value;
		let month2 = month.value - 2 < 0 ? 11 : month.value - 2;
		year.value = year1
		month.value = (month2 + 1)
		dayIndex.value = -1
		signInTime.value = ''
		dateInit(year.value, month.value);
		yesdate()
	}
 
    // ---------------------------------------------------------------------------------------下一月切换------------------------------------------------------------------------------
	const nextMonth = () => {
		//全部时间的月份都是按0~11基准，显示月份才+1
		let year1 = month.value > 11 ? year.value + 1 : year.value;
		let month2 = month.value > 11 ? 0 : month.value;
		year.value = year1
		month.value = (month2 + 1)
		dayIndex.value = -1
		signInTime.value = ''
		dateInit(year.value, month.value);
		yesdate()
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #140002;
	}

	.title {
		text-align: center;
		width: 100%;
		padding-bottom: 37rpx;
		font-family: PingFang SC;
		font-weight: bold;
		font-size: 36rpx;
		color: #212121;
		line-height: 36rpx;
	}

	.contant {
		/* background: #fff;*/
		padding: 10rpx 24rpx;

		.banner {
			image {
				width: 100%;
				height: auto;
				vertical-align: middle;
			}
		}
	}

	.calendar_title {
		color: #fff;
		padding: 30rpx 0;
		box-sizing: border-box;
		font-size: 28rpx;
		/**/
		display: flex;
		align-items: center;
		justify-content: flex-end;
		padding: 0;
		/* padding-top: 30rpx;*/
		margin-right: 20rpx;
	}

	.calendar_title .icon {
		width: 40rpx;
		height: 40rpx;
		font-size: 0;
	}

	.icon image {
		width: 100%;
		height: 100%;
	}

	.nowDtae {
		color: #212121;
		/**/
		/* color: rgba($color: #fff, $alpha: 0.9);*/
		margin: 0 20rpx;
	}

	/* 日历 */
	.calendar {
		width: 100%;
		background: #ffffff;
		/* opacity: .8;*/
		border-radius: 20rpx;
		padding: 0 0 20rpx;
		margin-top: 20rpx;

		.TDate {
			/* color: rgba($color: #fff, $alpha: 0.9);*/
			box-sizing: border-box;
			padding: 0 20rpx;
			padding-top: 20rpx;
			font-size: 30rpx;

			.TMonth {
				color: #ffaa00;
			}

			.TDay {
				color: #ff3b3b;
				font-size: 42rpx;
				padding: 0 16rpx;
			}
		}
	}

	.header {
		font-size: 0;
		width: 100%;
		margin: 0 auto;
	}

	.header>view {
		display: inline-block;
		width: 14.285%;
		color: #666666;
		font-size: 26rpx;
		text-align: center;
		/* border-bottom: 1px solid #D0D0D0;*/
		padding: 20rpx 0;
	}

	.weekMark {
		position: relative;
		width: 80%;
		margin: 0 auto;
	}

	.weekMark view {
		position: absolute;
		bottom: 0;
		left: 0;
		width: 100%;
		/* border-bottom: 2px solid #69f;*/
	}

	.date-box {
		padding: 10rpx 0;
		width: 100%;
		margin: 0 auto;
		/* height: 830rpx;*/
	}

	.date-box>view {
		position: relative;
		display: inline-block;
		width: 14.285%;
		color: #666;
		text-align: center;
		vertical-align: middle;
	}

	.date-head {
		height: 60rpx;
		line-height: 60rpx;
		color: #999999;
		font-size: 26rpx;
	}

	.date-top {
		font-size: 22rpx;
		background: #e6e6e6;
		color: #fff;
		margin: 0 8rpx;
		border-radius: 10rpx;
		box-sizing: border-box;
		/* padding: 8rpx 0;*/
		width: 84rpx;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		>view {
			image {
				margin-top: 6rpx;
				width: 34rpx;
				height: 34rpx;
			}
		}
	}

	.agoDays .date-top {
		background-color: #e6e6e6;
	}

	.agoDays .date-topT {
		background-color: #ffcc66;
	}

	.nextDays .date-top image {
		width: 40rpx;
		height: 40rpx;
	}

	.nowDay .date-top {
		background-color: #ffcc66;
		border: 2rpx solid #ff3333;
		color: #ff3333;
	}

	.nowDay .date-topT {
		background-color: #ffcc66;
		color: #fff;
	}

	.nowDay .date-top image {
		width: 34rpx;
		height: 34rpx;
	}

	.dayIndex {
		border: 2rpx solid #ff3333;
	}

	/* 签到 */
	.center {
		background: #ff6a00;
		padding: 22rpx 0;
		box-sizing: border-box;
		margin: 20rpx auto;
		width: 400rpx;
		text-align: center;
		border-radius: 60rpx;
	}

	.center_text {
		/* margin-top: 20rpx;*/
		color: #fff;
		font-size: 30rpx;
		letter-spacing: 2rpx;
	}

	.center_texts {
		color: #fff;
	}

	.bottom_text {
		font-weight: normal;
		line-height: 60rpx;
	}

	.bottom_text text {
		color: #66afff;
	}

	.bottom {
		background: #fff;
		padding: 60rpx 0;
		box-sizing: border-box;
	}

	.rewardContent {
		background-color: #ffffff;
		margin-top: 20rpx;
		border-radius: 20rpx;

		/* color: rgba($color: #fff, $alpha: 0.8);*/
		.rewardTitle {
			font-size: 30rpx;
			padding: 30rpx 20rpx;
		}

		.rewardList {
			display: flex;
			align-items: center;
			justify-content: space-between;
			flex-wrap: wrap;
			margin: 0 20rpx;

			.rewardItem {
				width: 31.5%;
				background-image: url('https://jtmc.oss-cn-hangzhou.aliyuncs.com/wmp/qnjg/signin/reward.png');
				background-size: 100% 100%;
				position: relative;
				box-sizing: border-box;
				padding: 14rpx;
				padding-top: 40rpx;
				font-size: 30rpx;
				margin-bottom: 20rpx;
				color: #fff;

				.rewardItem-day {
					background-image: url('https://jtmc.oss-cn-hangzhou.aliyuncs.com/wmp/kbq/common/i_icon_signTip.png');
				}

				.itemAbsT {
					position: absolute;
					right: 4rpx;
					top: 4rpx;
					font-size: 24rpx;
					/* isGetAward*/
					background-color: #e6bf73;
					padding: 2rpx 10rpx;
					border-radius: 30rpx;
					color: #ffffff;
				}

				.itemAbsF {
					position: absolute;
					right: 4rpx;
					top: 4rpx;
					font-size: 24rpx;
					background-color: #ffaa00;
					color: #ffffff;
					padding: 2rpx 10rpx;
					border-radius: 30rpx;
				}

				view {
					line-height: 1.6;
				}
			}
		}
	}

	.ruleContent {
		background-color: #fff;
		margin: 20rpx 0;
		border-radius: 20rpx;
		/* color: rgba($color: #fff, $alpha: 0.8);*/
		box-sizing: border-box;
		padding: 30rpx 20rpx;

		.ruleTitle {
			font-size: 40rpx;
			padding-bottom: 20rpx;
		}

		.ruleText {
			font-size: 28rpx;
			text-align: justify;
			color: #999999;
			line-height: 1.8;
		}
	}
</style>